from flask import Blueprint, jsonify, request
from app.models.Skillc2 import User, UserProfile
from app import db
from werkzeug.security import generate_password_hash, check_password_hash
from flask_jwt_extended import create_access_token, jwt_required, get_jwt_identity
from datetime import datetime

user_bp = Blueprint('user', __name__)



@user_bp.route('/users', methods=['GET'])
@jwt_required()
def get_users():
    """获取所有用户列表"""
    try:
        # 获取当前用户ID
        user_id = int(get_jwt_identity())

        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)

        users = User.query.paginate(page=page, per_page=per_page)

        return jsonify({
            'status': 'success',
            'data': [{
                'id': user.UserId,
                'username': user.UserName,
                'email': user.UserEmail,
                'balance': float(user.UserBalance or 0),
                'points': int(user.UserPoints or 0)
            } for user in users.items],
            'total': users.total,
            'pages': users.pages,
            'current_page': page
        })
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500


@user_bp.route('/users/<int:user_id>', methods=['GET'])
@jwt_required()
def get_user(user_id):
    """获取单个用户信息"""
    try:
        # 获取当前用户ID
        user_id = int(get_jwt_identity())
        
        # 直接使用 filter_by 而不是 get_or_404
        user = User.query.filter_by(UserId=user_id).first()
        
        if not user:
            return jsonify({
                'status': 'error',
                'message': f'未找到ID为 {user_id} 的用户'
            }), 404
            
        return jsonify({
            'status': 'success',
            'data': {
                'id': user.UserId,
                'username': user.UserName,
                'email': user.UserEmail,
                'balance': float(user.UserBalance or 0),
                'points': int(user.UserPoints or 0)
            }
        })
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500


@user_bp.route('/users', methods=['POST'])
def create_user():
    """创建新用户"""
    try:
        data = request.get_json()
        user = User(
            UserName=data['username'],
            UserPassword=data['password'],
            UserEmail=data['email']
        )
        user.save()
        return jsonify({
            'status': 'success',
            'message': '用户创建成功',
            'data': {
                'id': user.UserId,
                'username': user.UserName,
                'email': user.UserEmail
            }
        }), 201
    except Exception as e:
        return jsonify({'status': 'error', 'message': str(e)}), 500


@user_bp.route('/users/register', methods=['POST'])
def register_user():
    """注册新用户"""
    try:
        data = request.get_json()

        # 验证输入数据
        if not data or not data.get('username') or not data.get('password') or not data.get('email'):
            return jsonify({
                'status': 'error',
                'message': '缺少必要的字段'
            }), 400

        username = data['username']
        password = data['password']
        email = data['email']

        # 检查用户是否已存在
        existing_user = User.query.filter_by(UserName=username).first()
        if existing_user:
            return jsonify({
                'status': 'error',
                'message': '用户已存在'
            }), 400

        # 加密密码
        hashed_password = generate_password_hash(password, method='pbkdf2:sha256')

        # 创建用户对象
        user = User(
            UserName=username,
            UserPassword=hashed_password,
            UserEmail=email
        )
        db.session.add(user)
        
        # 创建用户信息记录
        profile = UserProfile(
            Nickname=username,  # 默认使用用户名作为昵称
            LastLoginTime=datetime.now()
        )
        user.profile = profile
        
        db.session.commit()

        return jsonify({
            'status': 'success',
            'message': '用户注册成功',
            'data': user.to_dict()
        }), 201

    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500


@user_bp.route('/users/login', methods=['POST'])
def login_user():
    """用户登录"""
    try:
        data = request.get_json()

        if not data or not data.get('username') or not data.get('password'):
            return jsonify({
                'status': 'error',
                'message': '缺少必要的字段'
            }), 400

        username = data['username']
        password = data['password']

        user = User.query.filter_by(UserName=username).first()
        if not user:
            return jsonify({
                'status': 'error',
                'message': '用户不存在'
            }), 404

        if not check_password_hash(user.UserPassword, password):
            return jsonify({
                'status': 'error',
                'message': '密码错误'
            }), 401

        # 更新最后登录时间
        if user.profile:
            user.profile.LastLoginTime = datetime.now()
        else:
            profile = UserProfile(
                UserId=user.UserId,
                Nickname=username,
                LastLoginTime=datetime.now()
            )
            db.session.add(profile)
        
        db.session.commit()

        access_token = create_access_token(identity=str(user.UserId))

        return jsonify({
            'status': 'success',
            'message': '登录成功',
            'data': {
                'access_token': access_token,
                'user': user.to_dict()
            }
        }), 200

    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@user_bp.route('/users/profile', methods=['GET'])
@jwt_required()
def get_user_profile():
    """获取用户个人信息"""
    try:
        user_id = int(get_jwt_identity())
        user = User.query.get(user_id)
        if not user:
            return jsonify({
                'status': 'error',
                'message': '用户不存在'
            }), 404
        
        return jsonify({
            'status': 'success',
            'data': user.to_dict()
        })
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@user_bp.route('/users/profile', methods=['PUT'])
@jwt_required()
def update_user_profile():
    """更新用户个人信息"""
    try:
        user_id = int(get_jwt_identity())
        user = User.query.get(user_id)
        if not user:
            return jsonify({
                'status': 'error',
                'message': '用户不存在'
            }), 404

        # 获取或创建用户信息记录
        profile = user.profile
        if not profile:
            profile = UserProfile(UserId=user_id)
            db.session.add(profile)

        data = request.get_json()
        allowed_fields = {
            'nickname': 'Nickname',
            'avatar': 'Avatar',
            'bio': 'Bio',
            'gender': 'Gender',
            'school': 'School',
            'department': 'Department'
        }

        # 更新用户信息
        for key, field in allowed_fields.items():
            if key in data:
                setattr(profile, field, data[key])

        profile.UpdateTime = datetime.now()
        db.session.commit()

        return jsonify({
            'status': 'success',
            'message': '个人信息更新成功',
            'data': user.to_dict()
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@user_bp.route('/users/password', methods=['PUT'])
@jwt_required()
def update_password():
    """修改密码"""
    try:
        user_id = int(get_jwt_identity())
        user = User.query.get(user_id)
        if not user:
            return jsonify({
                'status': 'error',
                'message': '用户不存在'
            }), 404

        data = request.get_json()
        if not data or not data.get('old_password') or not data.get('new_password'):
            return jsonify({
                'status': 'error',
                'message': '缺少必要的字段'
            }), 400

        # 验证旧密码
        if not check_password_hash(user.UserPassword, data['old_password']):
            return jsonify({
                'status': 'error',
                'message': '原密码错误'
            }), 400

        # 更新密码
        user.UserPassword = generate_password_hash(data['new_password'], method='pbkdf2:sha256')
        user.UpdateTime = datetime.now()
        db.session.commit()

        return jsonify({
            'status': 'success',
            'message': '密码修改成功'
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500
